//
//  WebVc.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/3/6.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

import JavaScriptCore
import HandyJSON


@objc protocol ActivityJavaScriptDelegate: JSExport {
    func getUserInfo() -> Int
    func getProgramId() -> Int
    func loginAction()
    func toHome()
    func toShare()
    func toRewordTbDetail()
    func toShareFreeListening()
    func toProgramDetail(num:Int)
}

@objc class ActivityJavaScriptModel: NSObject, ActivityJavaScriptDelegate {
   
    weak var controller: UIViewController?
    weak var jsContext: JSContext?
    
    func loginAction() {
        
    }
    
    func getUserInfo() -> Int {
        return String.getUserId()
        
    }
    
    func getProgramId() -> Int {
        return 88
        
    }
    
    func toHome() {
        DispatchQueue.main.sync {
            self.controller?.dismiss(animated: true, completion: {
                let mainVC = TTTabBarController()
                AppDelegate.getAppDelegate().window?.rootViewController = mainVC
                mainVC.selectedIndex = 0
            })
            
        }
    }
    
    func toShare() {
        DispatchQueue.main.sync {
            HomeRequestModel.loadResourcesData(parameters: ["flg":"go_download"]) { (success, message, urlStr) in
                if success {
                    let newUrl = urlStr + "?srcUserId=\(String.getUserId())"
                    let share = ShareView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), title: "天天必听", des: "分享免费听", url: newUrl ?? "https://itunes.apple.com/cn/app/天天必听/id1449930721", image: "http://source.blistening.cn/bt_source/ttbt/logo/logo.png")
                    UIApplication.shared.keyWindow?.addSubview(share)
                }
            }
        }
    }
    
    func toRewordTbDetail() {
        DispatchQueue.main.sync {
            self.controller?.dismiss(animated: true, completion: {
//                let mainVC = TTTabBarController()
//                AppDelegate.getAppDelegate().window?.rootViewController = mainVC
//                mainVC.selectedIndex = 1
                let vc = TBWithdrawVc()
                PUSHVIEWCONTROLLER(vc)
            })

        }
    }
    
    func toShareFreeListening() {
        DispatchQueue.main.sync {
            self.controller?.dismiss(animated: true, completion: {
//                let mainVC = TTTabBarController()
//                AppDelegate.getAppDelegate().window?.rootViewController = mainVC
//                mainVC.selectedIndex = 1
                let vc = ShareFreeListenVc()
                PUSHVIEWCONTROLLER(vc)
            })
            
        }
    }
    
    func toProgramDetail(num: Int) {
        DispatchQueue.main.sync {
            self.controller?.dismiss(animated: true, completion: {
                let mainVC = TTTabBarController()
                AppDelegate.getAppDelegate().window?.rootViewController = mainVC
                mainVC.selectedIndex = 0
                let vc = PlayVC()
                vc.id = num
                PUSHVIEWCONTROLLER(vc)
            })
            
        }
        
    }
    
    
}

class WebVc: UIViewController, UIWebViewDelegate {
    var backView:UIView = {
        let view = UIView.init(frame: FRAME_CGFloat(0, 2, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP - 2))
        view.backgroundColor = WhiteBackColor
        
        let imageView = UIImageView.init(frame: FRAME_CGFloat(SCREEN_WIDTH / 2 - 81, 60, 162, 228))
        imageView.image = IMAGE(name: "placeholderImage")
        view.addSubview(imageView)
        
        let imageLabel = UILabel.init(frame: FRAME_CGFloat(0, 300, SCREEN_WIDTH, 20))
        imageLabel.text = "小编正在努力搬运上传哦~"
        imageLabel.font = Font_Semibold(14)
        imageLabel.textColor = RGB_Same(178)
        imageLabel.textAlignment = .center
        view.addSubview(imageLabel)
        
        return view
    }()
    var titleLabel:UILabel?
    var leftButton:UIButton?
    
    //  MARK: - ###### 产品寿命 ######
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        
        setHeadUI()
        setupUI()
        prepare()
        
        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //  MARK: - ###### 子视图 ######
    
    //  MARK: - ###### 变量 ######
    var webView:UIWebView = {
        let webView = UIWebView(frame: CGRect(x: 0, y: OFFSET_TOP, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - OFFSET_TOP))
        webView.backgroundColor = .white
        return webView
    }() //webView
    var urlString:String?//webView加载地址
    var processColor:UIColor? //加载进度条颜色
    var processLine:WebViewProgressLine = {
        let line = WebViewProgressLine(frame: CGRect(x:0, y:0, width:SCREEN_WIDTH, height:2), lineColr: UIColor.green)
        return line
    }()
    var delegate:WebViewDelegate?
    var jsContext: JSContext!
    
    
    
}

//  MARK: - ###### 协议 ######
extension WebVc{
    //  MARK: - ###### UIWebViewDelegate
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
       
        
        return true
    }
 
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        processLine.startLoadingAnimation()
        self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
        let model = ActivityJavaScriptModel()
        model.controller = self
        model.jsContext = self.jsContext
        
        self.jsContext.setObject(model, forKeyedSubscript: "WebViewJavascriptBridge" as NSCopying & NSObjectProtocol)
        
        // 注册到网络Html页面 请设置允许Http请求
        let url = NSURL.init(string: urlString ?? "")
        
        let curUrl = webView.request?.url?.absoluteString
        if curUrl != "" && url != nil {
            self.jsContext.evaluateScript(try? String(contentsOf: url! as URL, encoding: String.Encoding.utf8))
            
            self.jsContext.exceptionHandler = { (context, exception) in
                print("exception：", exception as Any)
            }
        }
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        processLine.endLoadingAnimation()
        backView.isHidden = true
        self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
        let model = ActivityJavaScriptModel()
        model.controller = self
        model.jsContext = self.jsContext
        
        self.jsContext.setObject(model, forKeyedSubscript: "WebViewJavascriptBridge" as NSCopying & NSObjectProtocol)
        
        // 注册到网络Html页面 请设置允许Http请求
        let url = NSURL.init(string: urlString ?? "")
        
        let curUrl = webView.request?.url?.absoluteString
        if curUrl != "" && url != nil {
            self.jsContext.evaluateScript(try? String(contentsOf: url as! URL, encoding: String.Encoding.utf8))
            
            self.jsContext.exceptionHandler = { (context, exception) in
                print("exception：", exception as Any)
            }
        }
        
        //读取webview页面的标题
        let title = webView.stringByEvaluatingJavaScript(from: "document.title")
        self.titleLabel?.text = title ?? ""

        
    }
}

//  MARK: - ###### 事件处理 ######
//  MARK: - ###### 协议 ######
extension WebVc{
    
}

//  MARK: - ###### 私有方法 ######
extension WebVc {
    fileprivate func setHeadUI() {
        titleLabel = UILabel.init(frame: CGRect.init(x: SCREEN_WIDTH/2 - 100, y: UIApplication.shared.statusBarFrame.size.height, width: 200, height: 44))
        titleLabel!.textAlignment = .center
        titleLabel!.adjustsFontSizeToFitWidth = true;
        titleLabel!.textColor = RGBHEX(0x303030)
        titleLabel!.font = UIFont.boldSystemFont(ofSize: 18)
        titleLabel!.autoresizing(index: 1)
        self.view.addSubview(titleLabel!)
        
        leftButton = UIButton(type: .custom)
        leftButton?.frame = CGRect.init(x: 10, y: UIApplication.shared.statusBarFrame.size.height + 14, width: 13, height: 20)
        
        leftButton?.setImage(IMAGE(name: "back"), for: .normal)
        leftButton?.imageView?.contentMode = .left
        leftButton?.addTarget(self, action: #selector(backAction), for: .touchUpInside)
        self.view.addSubview(leftButton!)
    }
    fileprivate func setupUI() {
        view.addSubview(webView)
        webView.delegate = self
        webView.addSubview(processLine)
        SET_LINEVIEW(view: view)
        webView.addSubview(backView)
    }
    fileprivate func prepare() {
        loadUrl(url: urlString)
        
        
    }
}

//  MARK: - ###### 公有方法 ######
extension WebVc {
    func loadUrl(url:String?) {
        if url == nil || url == "" {
            return
        }
        urlString = url
        let URLTmp = URL.init(string: url?.trimmingCharacters(in: .whitespaces) ?? "")
        if URLTmp != nil {
            let request = URLRequest(url: URLTmp!)
            webView.loadRequest(request)
        }
        
    }
    
    @objc func backAction() {
        self.dismiss(animated: true, completion: nil)
    }
}
